<?php

namespace App\Models;

use App\Libraries\Common\CommonFun;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class RobotMessage extends Model
{
    use HasFactory;

    const UPDATED_AT = NULL;

    protected $table = 'robot_message';

    protected $fillable = [
        'article_id',
        'content',
        'status',
        'message'
    ];

    public static function lists($page = 1, $limit = 20, $params = []){
        $title=data_get($params,'title',false);

        $ary_where = array();
        $ary_where[] = ['is_del', '=', 0];
        $status=data_get($params,'status',false);

        if($status){
            $ary_where[] = ['status', '=', $status];
        }
        $data=RobotMessage::with(['article.material'])
            ->whereHas('article',function ($query) use($title){
                return $query->when(isset($title) && !empty($title), function($query) use($title){
                   return $query->where('title','like','%'.$title.'%');
                });
            })->where($ary_where)
          ->offset(CommonFun::getOffset($page, $limit))->limit($limit)->orderby('id', 'desc')
            ->get()->toArray();

        $count=RobotMessage::with(['article.material'])
            ->whereHas('article',function ($query) use($title){
                return $query->when(isset($title) && !empty($title), function($query) use($title){
                    return $query->where('title',$title);
                });
            })->where($ary_where)->count();

        return $data ? compact('count', 'data') : false;
    }

    public function article(){
        return $this->hasOne(Article::class,'id','article_id');
    }

    protected function serializeDate(\DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }
}
